import { HttpErrorResponse } from '@angular/common/http';
import { AfterContentInit, Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { concatMap, map } from 'rxjs/operators';
import { BoardCollectBoardGroupVo } from 'src/app/model/board-collect-board-group-vo';
import { BoardStatsVo } from 'src/app/model/board-stats-vo';
import { MemberVo } from 'src/app/model/member-vo';
import { BoardService } from 'src/app/services/board.service';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { UtilService } from 'src/app/services/util.service';
import { environment } from 'src/environments/environment';
@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styles: [``]
})
/**
 * 版块主页
 * @constructor
 */
export class DetailComponent implements OnInit, AfterContentInit {
  public item!: BoardCollectBoardGroupVo;
  public statsVo!: BoardStatsVo;
  public errorMessage: string = '';
  //当前分类|all:所有,tops:置顶,goods:精华,pic:图片,hots:火贴
  public threadsCategory: string = 'all';
  //当前页码
  public page: number = 1;
  //每页显示的数量
  public pageSize: number = 20;
  //是否可以收藏,true可以,false收藏过了
  public canFavorited: boolean = true;
  //当前登录的会员
  private curMember: MemberVo | null;
  private token: string;
  private ip:string = '127.0.0.1';

  constructor(
    private title: Title,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private boardService: BoardService,
    private memberStorage: MemberStorageService,
    private util: UtilService,
    private btnNaviSharedService: BtnNaviSharedService) {
    this.btnNaviSharedService.active(false); //不显示全局的导航
    this.curMember = this.memberStorage.get();
    this.token = this.util.randomAlphaNumeric(8) || '123456';
    this.memberStorage.getIpCliente().subscribe(ipAddr=>this.ip=ipAddr);
  }

  ngAfterContentInit(): void {
    let boardConstr = this.activatedRoute.snapshot.paramMap.get('constr') ?? '-';
    let y: number[] = this.parseConString(boardConstr);
    //this.unionCheckBoard(this.curMember?.id??0, y[0]);
  }

  ngOnInit(): void {
    let boardConstr = this.activatedRoute.snapshot.paramMap.get('constr') ?? '-';
    this.threadsCategory = this.activatedRoute.snapshot.queryParamMap.get('c') ?? 'all';
    this.page = +(this.activatedRoute.snapshot.queryParamMap.get('p') ?? 1);
    this.pageSize = +(this.activatedRoute.snapshot.queryParamMap.get('s') ?? environment.pageSize)
    //
    let y: number[] = this.parseConString(boardConstr);
    this.boardService.getCascade(y[0], y[1]).pipe(
      concatMap(
        (bcbg: BoardCollectBoardGroupVo) => this.boardService.getStats(y[0]).pipe(
          map(
            (stats: BoardStatsVo) => {
              return { stats: stats, data: bcbg };
            })
        ))).subscribe({
      next: response => {
        this.item = response.data;
        this.statsVo = response.stats;
        this.title.setTitle(this.item.boardVo.title);
      },
      error: err => {
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            this.errorMessage = err.error.message;
          } else {
            if (err.status === 404) {
              //跳转
              this.router.navigate(['404']);
            } else {
              this.errorMessage = err.error;
            }
          }
        } else if (err instanceof Error) {
          this.errorMessage = err.message;
        } else { this.errorMessage = err; }
        //ETC
      },
      complete: () => {
        console.log('[Board-CTL]Completed');
        this.isFavorited();
      }
    });
  }
  /**
   * 是否已经收藏过了
   * @deprecated
   */
  private isFavorited(): void {
    if (this.curMember !== null && this.item && this.item.boardVo) {
      this.boardService.isFavorited(this.item.boardVo.id, this.curMember.id).subscribe({
        next: response => {
          //console.log(response);
        },
        error: err => {
          if (err instanceof HttpErrorResponse && err.status === 417) {
            this.canFavorited = false;
          }
        },
        complete: () => {
          console.log('[Board-CTL]Favorite check Completed');
        }
      });
    }
  }
  /**
   * 联合点赞,收藏检查
   * @param memberId 
   * @param topicId 
   */
  private unionCheckBoard(memberId: number, boardId: number): void{
    if (memberId > 0 && boardId>0) {
      this.boardService.getSSEUnionCheckResult(boardId, memberId).subscribe(res=>{
        if(res.id === boardId){
          this.canFavorited = parseInt(res.favorite)>0?true:false;
        }
      });
    }
  }

  /**
   * 从地址(/board/:constr)中提取相关主键
   * @param constr 
   */
  private parseConString(constr: string): number[] {
    if (typeof constr != 'undefined' && constr) {
      let x: string[] = constr.replace('.xhtml', '').split('-');
      if (x.length != 2) { return []; }
      return x.map((ele: string) => parseInt(ele) ?? 0);
    }
    return [];
  }

  //收藏版块
  public favorite(event: Event) {
    if (this.statsVo) {
      //REST API
      this.boardService.favorite(this.statsVo.boardId, this.curMember?.id ?? 0, this.curMember?.nickname ?? 'guest', this.token, this.ip).subscribe({
        next: response => {
          this.statsVo.favorites += 1;
          this.canFavorited = false;
        },
        error: err => {
          let em: string = '';
          if (err instanceof HttpErrorResponse) {
            if (err.error instanceof ErrorEvent) {
              em = err.error.message;
            } else {
              em = (err.status == 417) ? '操作失败' : err.error;
            }
          } else if (err instanceof Error) {
            em = err.message;
          } else { em = err; }
          this.util.alertError(em);
          console.log('[Board-CTL]favorite error ' + em);
        },
        complete: () => { console.log('[Board-CTL]Favorite Completed'); }
      });
    }
  }
}
